const std = @import("std");
const jetzig = @import("jetzig");
const article_service = @import("../service/article_service.zig");
const cate_service = @import("../service/cate_service.zig");
const article_model = @import("../model/article.zig");

/// 首页
pub fn index(req: *jetzig.Request, data: *jetzig.Data) !jetzig.View {
    var root = try data.object();

    // 文章列表数据
    var arts_array = try data.array();
    const articles = try article_service.getHomeArticles();

    // std.debug.print("articles: {any}\n", .{articles});
    std.sort.block(article_model.Article, articles, {}, lessThan);
    // std.debug.print("articles: {any}\n", .{articles});

    for (articles) |art| {
        var art_obj = try data.object();
        try art_obj.put("id", data.integer(art.id));
        try art_obj.put("title", data.string(art.title));
        try art_obj.put("description", data.string(art.description));
        try art_obj.put("content", data.string(art.content));
        try art_obj.put("istop", data.boolean(art.istop == 1));
        try art_obj.put("cate_name", data.string(art.cate_name));
        try art_obj.put("created_at", data.string(art.created_at));

        try arts_array.append(art_obj);
    }
    try root.put("articles", arts_array);

    // 分类列表数据
    var cates_array = try data.array();
    const cates = try cate_service.getHomeCategories();
    for (cates) |cate| {
        var cate_obj = try data.object();
        try cate_obj.put("id", data.integer(cate.id));
        try cate_obj.put("name", data.string(cate.name));

        try cates_array.append(cate_obj);
    }
    try root.put("cates", cates_array);

    return req.render(.ok);
}

/// 比较函数
fn lessThan(context: void, a: article_model.Article, b: article_model.Article) bool {
    _ = context;
    return b.istop < a.istop;
}
